package com.seashop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.seashop.constant.RedisConstant;
import com.seashop.redis.RedisZero;
import com.seashop.response.LoginResponse;
import com.seashop.response.ResponseBase;
import com.seashop.constant.BaseConstant;
import com.seashop.entity.User;
import com.seashop.request.LoginRequestParam;
import com.seashop.service.IUserService;
import com.seashop.util.BeanCopyUtil;
import com.seashop.util.CheckMobileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

/**
 * @author moredln
 * @desc 登陆功能
 * @date 2020-10-31 11:08
 */
@RestController
@Api(tags = "登陆中心")
@Slf4j
@Validated
public class LoginController {

    @Value("${system.mobileList}")
    private List<String> mobileList;
    @Value("${system.defaultCode}")
    private String defaultCode;

    @Autowired
    private IUserService userService;
    @Autowired
    private RedisZero redisZero;

    @GetMapping("/logout")
    @ApiOperation(value = "退出登陆")
    public ResponseBase logout(@NotBlank @RequestParam("Authorization") String authorization) {
        try {
            redisZero.delete(authorization);
            return ResponseBase.success();
        } catch (Exception e) {
            log.error("logout.failed");
        }
        return ResponseBase.fail("logout.failed");
    }

    @GetMapping("/getVerificationCode")
    @ApiOperation(value = "获取短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "电话号码", name = "mobile", dataType = "string", required = true),
            @ApiImplicitParam(value = "地区编码(66:泰国;62:印尼;86:中国;1:美国;03:巴基斯坦;)", name = "areaCode", dataType = "string", required = true),
            @ApiImplicitParam(value = "国家编码(TH:泰国;IN:印尼;ZH:中国;US:美国;UR:巴基斯坦;)", name = "countryCode", dataType = "string", required = true)
    })
    public ResponseBase getVerificationCode(@NotBlank String mobile, @NotBlank String areaCode, @NotBlank String countryCode) {
        // 根据国家编码，验证手机号码格式正确性
        ResponseBase checkResult = CheckMobileUtil.checkMobile(mobile, areaCode);
        if (null != checkResult) {
            return checkResult;
        }
        // 获取手机验证码
        int result = userService.getVerificationCode(mobile, areaCode, countryCode);
        if (result == 3) {
            return ResponseBase.success();
        } else if (result == 2) {
            ResponseBase.fail("The interval is not more than one minute, please try again after one minute!");
        } else if (result == 1) {
            ResponseBase.fail("The limit was exceeded today, please try again tomorrow!");
        }
        return ResponseBase.fail(BaseConstant.MSG_CODE_FAIL);
    }

    @PostMapping("/loginOrRegister")
    @ApiOperation(value = "手机号码登陆注册")
    public ResponseBase<LoginResponse> loginOrRegister(@Valid @RequestBody LoginRequestParam param) {
        String mobile = param.getMobile();
        String verifyCode = param.getVerifyCode();
        String areaCode = param.getAreaCode();
        // 根据国家编码，验证手机号码格式正确性
        ResponseBase checkResult = CheckMobileUtil.checkMobile(mobile, areaCode);
        if (null != checkResult) {
            return checkResult;
        }
        // 验证验证码是否正确
        String redisMobile = RedisConstant.MSG_CODE_PREFIX + areaCode + mobile;
        if (!redisZero.exists(redisMobile)) {
            return ResponseBase.fail(BaseConstant.GET_VERFITY_CODE_AGAIN);
        }
        String redisCode = redisZero.get(redisMobile).toString();
        log.info("Redis获取验证码：" + redisCode);
        if (!(verifyCode.equals(redisCode))) {
            return ResponseBase.fail(BaseConstant.VERFITY_CODE_ERROR);
        }
        User user = userService.getOne(new QueryWrapper<User>().eq("mobile", areaCode + mobile));
        LoginResponse response = new LoginResponse();
        if (null == user) {
            // 没有则注册
            int result = userService.register(param);
            if (result == 0) {
                return ResponseBase.fail("register fail");
            }
            user = userService.getOne(new QueryWrapper<User>().eq("mobile", areaCode + mobile));
            response = BeanCopyUtil.copy(user, LoginResponse.class);
            response.setIsRegister(true);
        } else {
            response = BeanCopyUtil.copy(user, LoginResponse.class);
            response.setIsRegister(false);
        }
        Integer userId = response.getUserId();
        String userToken = userService.updateToken(userId);
        response.setUserToken(userToken);
        // 注册登陆成功后清除redis验证码，避免多方登陆
        redisZero.delete(redisMobile);
        log.info("Redis清除验证码完成");
        return ResponseBase.success(response);
    }

}
